package io.xxx.omni.sync.impl

import com.alibaba.fastjson.JSON
import io.xxx.omni.sync.Document
import io.xxx.omni.sync.Porter
import io.xxx.omni.sync.Store
import io.xxx.omni.util.dateTimeFormatter
import io.xxx.omni.util.toLocalDateTime
import org.springframework.http.HttpHeaders
import org.springframework.stereotype.Component
import org.springframework.web.util.UriComponentsBuilder
import java.net.URI
import java.time.LocalDateTime

/**
 * 淘宝
 */
abstract class TbPorter : Porter() {

    private val httpUrl = "https://39.100.8.158:3389/api"

    override val platformCode = "taobao"

    protected abstract val path: String

    override fun getUrl(store: Store, startTime: LocalDateTime, endTime: LocalDateTime, parameter: Any?): URI {
        return UriComponentsBuilder.fromHttpUrl(httpUrl)
            .path(path)
            .queryParam("startTime", startTime.format(dateTimeFormatter))
            .queryParam("endTime", endTime.format(dateTimeFormatter))
            .queryParam("storeCode", store.code)
            .build(false)
            .toUri()
    }

    override fun getHeaders(): HttpHeaders? {
        val headers = HttpHeaders()
        headers.add("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.e30.hofgCo40uCztlOGBSu8P5wpvrG8ahEpY4AyDLM6WgaY")
        return headers
    }
}

@Component
class TbTradePorter : TbPorter() {

    override val jobId = 1

    override val path = ""

    override fun buildDocuments(data: List<String>): List<Document> {
        return data.map {
            val value = JSON.parseObject(it)
            val modified = value.getString("jdpModified").toLocalDateTime()
            Document(value.getString("tid"), value, modified)
        }
    }
}

@Component
class TbRefundPorter : TbPorter() {

    override val jobId = 2

    override val path = ""

    override fun buildDocuments(data: List<String>): List<Document> {
        return data.map {
            val value = JSON.parseObject(it)
            val modified = value.getString("jdpModified").toLocalDateTime()
            Document(value.getString("refundId"), value.getString("tid"), value, modified)
        }
    }
}